package com.aps.controller;

import com.aps.service.excel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Excel导入控制器
 */
@RestController
@RequestMapping("/api/excel")
@CrossOrigin(origins = "*")
public class ExcelImportController {
    
    @Autowired
    private ExcelImportService excelImportService;
    
    /**
     * 导入Excel数据
     */
    @PostMapping("/import")
    public ResponseEntity<Map<String, Object>> importExcel(
            @RequestParam("file") MultipartFile file,
            @RequestParam("entityName") String entityName,
            @RequestParam(value = "options", required = false) Map<String, Object> options) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 验证文件
            if (file.isEmpty()) {
                response.put("success", false);
                response.put("message", "文件不能为空");
                return ResponseEntity.badRequest().body(response);
            }
            
            // 验证文件类型
            String filename = file.getOriginalFilename();
            if (filename == null || (!filename.endsWith(".xlsx") && !filename.endsWith(".xls"))) {
                response.put("success", false);
                response.put("message", "只支持Excel文件格式");
                return ResponseEntity.badRequest().body(response);
            }
            
            // 验证文件大小
            if (file.getSize() > 10 * 1024 * 1024) { // 10MB
                response.put("success", false);
                response.put("message", "文件大小不能超过10MB");
                return ResponseEntity.badRequest().body(response);
            }
            
            // 执行导入
            ExcelImportResult result = excelImportService.importExcel(file, entityName, options);
            
            response.put("success", result.isSuccess());
            response.put("message", result.getMessage());
            
            Map<String, Object> data = new HashMap<>();
            data.put("successCount", result.getSuccessCount());
            data.put("failCount", result.getFailCount());
            data.put("errors", result.getErrors());
            response.put("data", data);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "导入失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 下载Excel模板
     */
    @PostMapping("/template")
    public ResponseEntity<byte[]> downloadTemplate(@RequestBody TemplateRequest request) {
        try {
            // 获取列配置
            List<ExcelColumnConfig> columns = getColumnConfigs(request.getEntityName());
            
            // 生成模板
            byte[] templateData = excelImportService.generateTemplate(request.getEntityName(), columns);
            
            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", getTemplateName(request.getEntityName()) + ".xlsx");
            
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(templateData);
                    
        } catch (Exception e) {
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 获取导入配置信息
     */
    @GetMapping("/config/{entityName}")
    public ResponseEntity<Map<String, Object>> getImportConfig(@PathVariable String entityName) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            List<ExcelColumnConfig> columns = getColumnConfigs(entityName);
            
            Map<String, Object> config = new HashMap<>();
            config.put("entityName", entityName);
            config.put("templateName", getTemplateName(entityName));
            config.put("columns", columns);
            config.put("uploadUrl", "/api/");
            config.put("templateUrl", "/api/excel/template");
            
            response.put("success", true);
            response.put("data", config);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取配置失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 验证Excel文件（不保存数据）
     */
    @PostMapping("/validate")
    public ResponseEntity<Map<String, Object>> validateExcel(
            @RequestParam("file") MultipartFile file,
            @RequestParam("entityName") String entityName) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 这里可以实现只验证不保存的逻辑
            // 临时实现：复用导入逻辑但不保存
            ExcelImportResult result = excelImportService.importExcel(file, entityName, null);
            
            response.put("success", true);
            response.put("valid", result.isSuccess());
            response.put("errors", result.getErrors());
            response.put("message", result.isSuccess() ? "验证通过" : "存在验证错误");
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "验证失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 获取列配置
     */
    private List<ExcelColumnConfig> getColumnConfigs(String entityName) {
        switch (entityName) {
            case "workOrder":
                return List.of(
                    new ExcelColumnConfig("workOrderId", "工单编号", "W-001", true, String.class),
                    new ExcelColumnConfig("orderId", "订单编号", "O-1001", true, String.class),
                    new ExcelColumnConfig("productId", "产品编号", "P-3001", true, String.class),
                    new ExcelColumnConfig("deliveryDate", "交付日", "2023-12-31", true, java.time.LocalDate.class),
                    new ExcelColumnConfig("quantity", "数量", "100", true, Integer.class),
                    new ExcelColumnConfig("priority", "优先级", "高", true, String.class)
                );
            case "device":
                return List.of(
                    new ExcelColumnConfig("deviceId", "设备编号", "DEV-001", true, String.class),
                    new ExcelColumnConfig("deviceName", "设备名称", "加工中心1号", true, String.class),
                    new ExcelColumnConfig("deviceType", "设备类型", "CNC", true, String.class),
                    new ExcelColumnConfig("capacity", "产能", "100", true, Integer.class),
                    new ExcelColumnConfig("status", "状态", "正常", true, String.class)
                );
            default:
                throw new RuntimeException("不支持的实体类型: " + entityName);
        }
    }
    
    /**
     * 获取模板名称
     */
    private String getTemplateName(String entityName) {
        switch (entityName) {
            case "workOrder":
                return "工单导入模板";
            case "device":
                return "设备导入模板";
            default:
                return "导入模板";
        }
    }
}

/**
 * 模板请求对象
 */
class TemplateRequest {
    private String entityName;
    private List<ExcelColumnConfig> columns;
    
    public TemplateRequest() {}
    
    // getters and setters
    public String getEntityName() { return entityName; }
    public void setEntityName(String entityName) { this.entityName = entityName; }
    
    public List<ExcelColumnConfig> getColumns() { return columns; }
    public void setColumns(List<ExcelColumnConfig> columns) { this.columns = columns; }
}
